<template>
  <div class="photo">
    <div class="box">
      <div class="tops">
        <van-nav-bar
          title="修改头像"
          @click-left="onClickLeft"
          right-text="保存"
          @click-right="onClickRight"
        >
          <template #left>
            <i class="iconfont iconbtn_nav_back"></i>
          </template>
        </van-nav-bar>
      </div>
    </div>
    <div class="content">
      <van-uploader
        v-model="fileList"
        multiple
        :after-read="afterRead"
        preview-size="200px"
        :show-upload="ishow"
        @delete="closed"
      />
    </div>
  </div>
</template>

<script>
// 导入bus方法
// import bus from '../../../utils/bus'
import { uploadAvatar, edit } from '../../../api/api'
// import { Toast } from 'vant'
export default {
  created () {
    // console.log('111')
  },
  data () {
    return {
      ishow: false,
      imgurl: '',
      fileList: [
        {
          url: this.$store.state.userInfo.avatar
        }
        // Uploader 根据文件后缀来判断是否为图片文件
        // 如果图片 URL 中不包含类型信息，可以添加 isImage 标记来声明
        // { url: this.$store.state.userInfo.avatar, isImage: true }
        // http://47.106.228.28:1337/${this.imgurl}
      ],
      // 头像id
      photoFileId: null
    }
  },
  methods: {
    onClickLeft () {
      this.$router.back()
    },
    // 完成文件上传后触发此事件
    async afterRead (file) {
      //   console.log('666')
      this.ishow = false
      // console.log('555', file.file)
      file.status = 'uploading'
      file.message = '上传中...'

      const res = await uploadAvatar(file.file)
      // console.log('what?', res)
      this.photoFileId = res.data[0]
      file.status = 'done'
      file.message = '上传中...'
      // console.log('11211', this.photoFileId)
    },
    // 保存头像按钮
    async onClickRight () {
      this.$store.state.userInfo.avatar =
        'http://47.106.228.28:1337' + this.photoFileId.url
      // console.log('???', this.photoFileId.url)
      await edit({ avatar: this.photoFileId.id })
      this.$toast.success('保存成功')
      this.$router.go(-1)
      // console.log('999', res1)
    },
    closed () {
      this.ishow = true
      console.log(this.$store.state.userInfo)
    }
  }
}
</script>

<style lang="less" scoped>
.photo {
  /deep/ .iconfont {
    font-size: 35px;
  }
  .content {
    margin-top: 30px;
    margin-left: 100px;
  }
}
</style>
